import os
import yaml
from loguru import logger
from backend.tools.tool_caller import ToolCaller

class ToolRegistry:
    _instance = None
    _initialized = False

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(ToolRegistry, cls).__new__(cls)
        return cls._instance

    def __init__(self):
        if self._initialized:
            return
        
        # 加载配置
        config_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), 'configs', 'config.yaml')
        with open(config_path, 'r', encoding='utf-8') as f:
            config = yaml.safe_load(f)        
            self.tools_config = config.get('tools', {})
        
        # 初始化工具调用器
        self.tool_caller = ToolCaller()
        
        # 初始化白名单
        self.tool_whitelist = self.tools_config.get('whitelisted_tools', [])
        
        # 初始化已注册的函数
        self.registered_functions = {}
        
        self._initialized = True
    
    def is_tool_registered(self, tool_name):
        """检查工具是否已注册"""
        available_tools = self.tool_caller.get_available_tools()
        return any(tool['name'] == tool_name for tool in available_tools)
    
    def is_tool_whitelisted(self, tool_name):
        """检查工具是否在白名单中"""
        return tool_name in self.tool_whitelist or bool(self.tools_config.get('enable_all_tools', False))
    
    def get_tool_info(self, tool_name):
        """获取工具信息"""
        available_tools = self.tool_caller.get_available_tools()
        for tool in available_tools:
            if tool['name'] == tool_name:
                return {
                    'name': tool['name'],
                    'description': tool['description'],
                    'parameters': tool['parameters'],
                    'enabled': tool['enabled'],
                    'whitelisted': self.is_tool_whitelisted(tool_name)
                }
        return None
    
    def is_tool_available(self, tool_name):
        """检查工具是否可用"""
        if not bool(self.tools_config.get('enabled', False)):
            return False
        
        tool_info = self.get_tool_info(tool_name)
        return tool_info is not None and tool_info['enabled'] and self.is_tool_whitelisted(tool_name)
    
    def get_registered_tools(self, show_details=False):
        """获取所有已注册的工具"""
        if not bool(self.tools_config.get('enabled', False)):
            return []
        
        available_tools = self.tool_caller.get_available_tools()
        tools_info = []
        
        for tool in available_tools:
            tool_data = {
                'name': tool['name'],
                'description': tool['description'],
                'available': bool(tool.get('enabled', False)) and self.is_tool_whitelisted(tool['name']),
                'whitelisted': self.is_tool_whitelisted(tool['name'])
            }
            
            if show_details:
                tool_data['parameters'] = tool.get('parameters', [])
                tool_data['enabled'] = bool(tool.get('enabled', False))
            
            tools_info.append(tool_data)
        
        return tools_info
    
    def is_function_registered(self, function_name):
        """检查函数是否已注册"""
        return function_name in self.registered_functions
    
    def get_function_info(self, function_name):
        """获取函数信息"""
        if function_name in self.registered_functions:
            return self.registered_functions[function_name]
        return None
    
    def register_function(self, function_name, function, description=''):
        """注册一个函数"""
        self.registered_functions[function_name] = {
            'name': function_name,
            'function': function,
            'description': description
        }
        logger.info(f"函数已注册: {function_name}")
    
    def unregister_function(self, function_name):
        """注销一个函数"""
        if function_name in self.registered_functions:
            del self.registered_functions[function_name]
            logger.info(f"函数已注销: {function_name}")

# 全局工具注册表实例
tool_registry = ToolRegistry()